package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.pay.config.RabbitMQConfig;
import com.changgou.pay.service.WxPayService;
import com.changgou.util.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: 大佬味的小男孩
 * @date: 2020-08-04 19:55
 **/
@RestController
@RequestMapping("wxpay")
public class WxPayController {

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * @param orderId
     * @param money
     * @return com.changgou.entity.Result
     * @description: 生成微信支付二维码
     * @author 大佬味的小男孩
     * @date 2020/08/04 20:12
     */
    @GetMapping("/nativePay")
    public Result nativePay(@RequestParam("orderId") String orderId, @RequestParam("money") Integer money) {
        Map map = wxPayService.nativePay(orderId, money);
        return new Result(true, StatusCode.OK, "", map);
    }


    /**
     * @param request
     * @param response
     * @return void
     * @description: 用户支付成功后，处理微信发送的消息
     * @author 大佬味的小男孩
     * @date 2020/08/05 15:03
     */
    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("支付成功回调");

        try {
            //1. 输入流转换为xml字符串
            String xml = ConvertUtils.convertToString(request.getInputStream());
            System.out.println(xml);

            //2. 基于微信发送的内容 ，完成支付状态查询
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            if (!"SUCCESS".equals(resultMap.get("result_code"))) {
                //如果支付状态不是成功的
                System.out.println(resultMap.get("err_code_des"));
                return;
            }
            // 3. 查询订单
            String orderId = resultMap.get("out_trade_no");
            Map map = wxPayService.queryOrder(orderId);
            if (!"SUCCESS".equals(map.get("result_code"))) {
                //如果查询订单状态不是成功的
                System.out.println(resultMap.get("err_code_des"));
                return;
            }
            // 4. 发送支付成功的消息到mq
            Map message = new HashMap();
            message.put("orderId", orderId);
            message.put("transactionId", map.get("transaction_id"));
            rabbitTemplate.convertAndSend("", RabbitMQConfig.ORDER_PAY, JSON.toJSONString(message));

            //5.完成双向通信
            rabbitTemplate.convertAndSend("paynotify", "", orderId);


            //6. 给微信返回结果通知
            response.setContentType("text/xml");
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param orderId
     * @return com.changgou.entity.Result
     * @description: 基于微信查询订单
     * @author 大佬味的小男孩
     * @date 2020/08/05 20:38
     */
    @GetMapping("query/{orderId}")
    public Result queryOrder(@PathVariable("orderId") String orderId) {
        Map resultMap = wxPayService.queryOrder(orderId);
        return new Result(true, StatusCode.OK, "查询订单成功", resultMap);
    }


    /**
     * @param orderId
     * @return com.changgou.entity.Result
     * @description: 基于微信关闭订单
     * @author 大佬味的小男孩
     * @date 2020/08/05 20:55
    */
    @PutMapping("close/{orderId}")
    public Result close(@PathVariable("orderId") String orderId) {
        Map resultMap = wxPayService.closeOrder(orderId);
        return new Result(true, StatusCode.OK, "关闭订单成功", resultMap);
    }
}
